package com.hc.app.aspect;

import cn.hutool.core.util.StrUtil;
import com.hc.utils.SpElUtils;
import com.hc.app.annatation.FrequencyControl;
import com.hc.app.constant.FrequencyControlConstant;
import com.hc.app.dto.FixWindowDTO;
import com.hc.app.dto.LeakBucketDTO;
import com.hc.app.dto.SlidingWindowDTO;
import com.hc.app.dto.TokenBucketDTO;
import com.hc.app.frequencycontrol.FrequencyControlUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import static com.hc.app.constant.FrequencyControlConstant.FIX_WINDOW;

/**
 * 限流切面
 */
@Aspect
@Component
public class FrequencyControlAspect {
    /**
     * 环绕通知
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("@annotation(com.hc.app.annatation.FrequencyControl)||@annotation(com.hc.app.annatation.FrequencyControlContainer)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        FrequencyControl[] annotationArr = method.getAnnotationsByType(FrequencyControl.class);
        HashMap<String, FrequencyControl> keyMap = new HashMap<>();
        String strategy = FIX_WINDOW;
        for (int i = 0; i < annotationArr.length; i++) {
            FrequencyControl frequencyControl = annotationArr[i];
            String prefix = StrUtil.isBlank(frequencyControl.prefixKey()) ? method.toGenericString() + ":index:" + i : frequencyControl.prefixKey();
            String key = "";
            switch (frequencyControl.target()) {
                case EL:
                    key = SpElUtils.parseSpEl(method, joinPoint.getArgs(), frequencyControl.spEl());
                    break;
                case IP:
                    key = "127.0.0.1";
                    break;
                case UID:
                    key = "1111111";
                    break;
                default:
                    break;
            }
            keyMap.put(prefix + ":" + key, frequencyControl);
            // for循环的最后一个频控策略，要求所用策略方式一样只是参数不同
            strategy = frequencyControl.strategy();
        }

        // 将注解的参数转换为编程式调用需要的参数
        if (FIX_WINDOW.equals(strategy)) {
            // 调用编程式注解 固定窗口
            List<FixWindowDTO> frequencyControlDTOS = keyMap.entrySet().stream().map(entrySet -> buildFixedWindowDTO(entrySet.getKey(), entrySet.getValue())).collect(Collectors.toList());
            return FrequencyControlUtil.executeWithFrequencyControlList(strategy, frequencyControlDTOS, joinPoint::proceed);
        } else if (FrequencyControlConstant.TOKEN_BUCKET.equals(strategy)) {
            // 调用编程式注解令牌桶
            List<TokenBucketDTO> frequencyControlDTOS = keyMap.entrySet().stream().map(entrySet -> buildTokenBucketDTO(entrySet.getKey(), entrySet.getValue())).collect(Collectors.toList());
            return FrequencyControlUtil.executeWithFrequencyControlList(strategy, frequencyControlDTOS, joinPoint::proceed);
        } else if(FrequencyControlConstant.SLIDING_WINDOW.equals(strategy)){
            // 调用编程式注解 滑动窗口
            List<SlidingWindowDTO> frequencyControlDTOS = keyMap.entrySet().stream().map(entrySet -> buildSlidingWindowDTO(entrySet.getKey(), entrySet.getValue())).collect(Collectors.toList());
            return FrequencyControlUtil.executeWithFrequencyControlList(strategy, frequencyControlDTOS, joinPoint::proceed);
        }else{
            // 调用编程式注解 漏桶
            List<LeakBucketDTO> frequencyControlDTOS = keyMap.entrySet().stream().map(entrySet -> buildLeakBucketDTO(entrySet.getKey(), entrySet.getValue())).collect(Collectors.toList());
            return FrequencyControlUtil.executeWithFrequencyControlList(strategy, frequencyControlDTOS, joinPoint::proceed);
        }
    }

    private LeakBucketDTO buildLeakBucketDTO(String key, FrequencyControl frequencyControl) {
        LeakBucketDTO leakBucketDTO = new LeakBucketDTO(frequencyControl.capacity(),frequencyControl.refillRate());
        leakBucketDTO.setKey(key);
        return leakBucketDTO;
    }

    /**
     * 将注解参数转换为编程式调用所需要的参数
     *
     * @param key              频率控制Key
     * @param frequencyControl 注解
     * @return 编程式调用所需要的参数-FrequencyControlDTO
     */
    private SlidingWindowDTO buildSlidingWindowDTO(String key, FrequencyControl frequencyControl) {
        SlidingWindowDTO frequencyControlDTO = new SlidingWindowDTO();
        frequencyControlDTO.setWindowSize(frequencyControl.windowSize());
        frequencyControlDTO.setPeriod(frequencyControl.period());
        frequencyControlDTO.setCount(frequencyControl.count());
        frequencyControlDTO.setUnit(frequencyControl.unit());
        frequencyControlDTO.setKey(key);
        return frequencyControlDTO;
    }

    /**
     * 将注解参数转换为编程式调用所需要的参数
     *
     * @param key              频率控制Key
     * @param frequencyControl 注解
     * @return 编程式调用所需要的参数-FrequencyControlDTO
     */
    private TokenBucketDTO buildTokenBucketDTO(String key, FrequencyControl frequencyControl) {
        TokenBucketDTO tokenBucketDTO = new TokenBucketDTO(frequencyControl.capacity(), frequencyControl.refillRate());
        tokenBucketDTO.setKey(key);
        return tokenBucketDTO;
    }

    /**
     * 将注解参数转换为编程式调用所需要的参数
     *
     * @param key              频率控制Key
     * @param frequencyControl 注解
     * @return 编程式调用所需要的参数-FrequencyControlDTO
     */
    private FixWindowDTO buildFixedWindowDTO(String key, FrequencyControl frequencyControl) {
        FixWindowDTO fixedWindowDTO = new FixWindowDTO();
        fixedWindowDTO.setCount(frequencyControl.count());
        fixedWindowDTO.setTime(frequencyControl.time());
        fixedWindowDTO.setUnit(frequencyControl.unit());
        fixedWindowDTO.setKey(key);
        return fixedWindowDTO;
    }
}
